package com.leetcode.sorts.tree;

import java.util.*;

/**
 * @Author: WuPeng
 * @Date: 2021/6/3 11:44 上午
 *
 * 107.二叉树的层序遍历2
 *
 */
public class LevelOrder2_107 {

    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> ret = new ArrayList<>();
        if (root == null){
            return ret;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        Deque<List<Integer>> deque = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()){
            List<Integer> level_list = new ArrayList<>();
            int level_size = queue.size();
            for (int i = 0; i < level_size; i++) {
                TreeNode node = queue.poll();
                level_list.add(node.val);
                if (node.left != null){
                    queue.offer(node.left);
                }
                if (node.right != null){
                    queue.offer(node.right);
                }
            }
            deque.push(level_list);
        }
        while (!deque.isEmpty()){
            ret.add(deque.pop());
        }
        return ret;
    }

}
